package com.jianan.mis.app.basedata;

import static com.jianan.mis.util.ui.calendar.SWTCalendarWrapper.openCalendar;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.domain.InternalOrganization;
import com.jianan.mis.data.domain.Session;
import com.jianan.mis.service.InternalOrganizationService;
import com.jianan.mis.sys.IGroupKeys;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.RegularUtils;
import com.jianan.mis.util.StringUtils;

public class InternalOrganizationView extends ViewPart {

	private Text txtContactEmail2;
	private Text txtContactPhone2;
	private Text txtContactName2;
	private Text txtContactEmail1;
	private Text txtContactPhone1;
	private Text txtContactName1;
	private Text txtCooperateEndDate;
	private Text txtCooperateStartDate;
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	class ListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			InternalOrganization organization = (InternalOrganization) element;
			return organization.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}
	private ComboViewer organizationComboViewer;
	private Combo organizationCombo;
	private Text txtName;
	
	public static final String ID = "com.jianan.mis.app.basedata.InternalOrganizationView"; //$NON-NLS-1$

	final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	
	private InternalOrganizationService internalOrganizationService;
	
	private InternalOrganization currentInternalOrganization;

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		
		if(!initializeServices()) {
			MessageDialog.openError(getViewSite().getShell(),
					IMessageKeys.OPEN_VIEW_FAIL, IMessageKeys.SERVICE_UNAVAILABLE);
			return;
		}
		
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.makeColumnsEqualWidth = true;
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label.setText("选择机构:");

		organizationComboViewer = new ComboViewer(container, SWT.READ_ONLY);
		organizationComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(final SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event.getSelection();
				currentInternalOrganization = (InternalOrganization) selection.getFirstElement();
				txtName.setText(currentInternalOrganization.getName());
				txtCooperateStartDate.setText(simpleDateFormat.format(currentInternalOrganization.getCooperateStartDate()));
				if (currentInternalOrganization.getCooperateEndDate() != null)
					txtCooperateEndDate.setText(simpleDateFormat.format(currentInternalOrganization.getCooperateEndDate()));
				txtContactName1.setText(currentInternalOrganization.getContactName1());
				txtContactPhone1.setText(currentInternalOrganization.getContactPhone1());
				txtContactEmail1.setText(currentInternalOrganization.getContactEmail1());
				if (currentInternalOrganization.getContactName2() != null)
					txtContactName2.setText(currentInternalOrganization.getContactName2());
				if (currentInternalOrganization.getContactPhone2() != null)
					txtContactPhone2.setText(currentInternalOrganization.getContactPhone2());
				if (currentInternalOrganization.getContactEmail2() != null)
					txtContactEmail2.setText(currentInternalOrganization.getContactEmail2());
			}
		});
		organizationComboViewer.setContentProvider(new ContentProvider());
		organizationComboViewer.setLabelProvider(new ListLabelProvider());
		organizationCombo = organizationComboViewer.getCombo();
		organizationCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		final GridData gd_combo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_combo.widthHint = 45;
		organizationCombo.setLayoutData(gd_combo);
		organizationComboViewer.setInput(internalOrganizationService.getAll());

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_1.setText("名称:");

		txtName = new Text(container, SWT.BORDER);
		final GridData gd_txtName = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		txtName.setLayoutData(gd_txtName);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("合作起始日期:");

		txtCooperateStartDate = new Text(container, SWT.BORDER);
		txtCooperateStartDate.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtCooperateStartDate, simpleDateFormat);
			}
		});
		final GridData gd_txtCooperateStartDate = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtCooperateStartDate.widthHint = 95;
		txtCooperateStartDate.setLayoutData(gd_txtCooperateStartDate);
		new Label(container, SWT.NONE);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_3.setText("合作终止日期:");

		txtCooperateEndDate = new Text(container, SWT.BORDER);
		txtCooperateEndDate.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtCooperateEndDate, simpleDateFormat);
			}
		});
		final GridData gd_txtCooperateEndDate = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtCooperateEndDate.widthHint = 95;
		txtCooperateEndDate.setLayoutData(gd_txtCooperateEndDate);
		new Label(container, SWT.NONE);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_4.setText("联系人1姓名(必填):");

		txtContactName1 = new Text(container, SWT.BORDER);
		final GridData gd_txtContactName1 = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContactName1.widthHint = 90;
		txtContactName1.setLayoutData(gd_txtContactName1);
		new Label(container, SWT.NONE);

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_5.setText("联系人1电话(必填):");

		txtContactPhone1 = new Text(container, SWT.BORDER);
		final GridData gd_txtContactPhone1 = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContactPhone1.widthHint = 130;
		txtContactPhone1.setLayoutData(gd_txtContactPhone1);
		new Label(container, SWT.NONE);

		final Label label_6 = new Label(container, SWT.NONE);
		label_6.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_6.setText("联系人1电邮(必填):");

		txtContactEmail1 = new Text(container, SWT.BORDER);
		final GridData gd_txtContactEmail1 = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContactEmail1.widthHint = 130;
		txtContactEmail1.setLayoutData(gd_txtContactEmail1);
		new Label(container, SWT.NONE);

		final Label label_7 = new Label(container, SWT.NONE);
		label_7.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_7.setText("联系人2姓名:");

		txtContactName2 = new Text(container, SWT.BORDER);
		final GridData gd_txtContactName2 = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContactName2.widthHint = 90;
		txtContactName2.setLayoutData(gd_txtContactName2);
		new Label(container, SWT.NONE);

		final Label label_8 = new Label(container, SWT.NONE);
		label_8.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_8.setText("联系人2电话:");

		txtContactPhone2 = new Text(container, SWT.BORDER);
		final GridData gd_txtContactPhone2 = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContactPhone2.widthHint = 130;
		txtContactPhone2.setLayoutData(gd_txtContactPhone2);
		new Label(container, SWT.NONE);

		final Label label_9 = new Label(container, SWT.NONE);
		label_9.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_9.setText("联系人1电邮:");

		txtContactEmail2 = new Text(container, SWT.BORDER);
		final GridData gd_txtContactEmail2 = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContactEmail2.widthHint = 130;
		txtContactEmail2.setLayoutData(gd_txtContactEmail2);
		new Label(container, SWT.NONE);

		final Button btnSave = new Button(container, SWT.NONE);
		btnSave.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (checkInfo()) {
					InternalOrganization organization = new InternalOrganization();
					fillOrganizationFields(organization);
					try {
						internalOrganizationService.save(organization);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "新增对内合作机构信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnSave = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
		btnSave.setLayoutData(gd_btnSave);
		btnSave.setText("添加机构");

		final Button btnUpdate = new Button(container, SWT.NONE);
		btnUpdate.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentInternalOrganization == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个机构!");
					return;
				}
				if (checkInfo()) {
					fillOrganizationFields(currentInternalOrganization);
					try {
						internalOrganizationService.update(currentInternalOrganization);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "更新对内合作机构信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnUpdate = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnUpdate.setLayoutData(gd_btnUpdate);
		btnUpdate.setText("更新机构");

		final Button btnRemove = new Button(container, SWT.NONE);
		btnRemove.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentInternalOrganization == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个机构!");
					return;
				}
				if(MessageDialog.openConfirm(e.display.getActiveShell(), 
						IMessageKeys.CONFIRM, "确认删除该机构吗?")) {
					try {
						internalOrganizationService.remove(currentInternalOrganization);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "删除对内合作信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
					}
				}
			}
		});
		btnRemove.setText("删除机构");
		
		if (Session.getInstance().getGroups().contains(IGroupKeys.MANAGER)) {
			btnRemove.setEnabled(true);
		} else {
			btnRemove.setEnabled(false);
		}
		
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	private boolean initializeServices() {
		internalOrganizationService = (InternalOrganizationService) SpringBeanFactory.getBean("internalOrganizationService");
		if(internalOrganizationService == null) {
			return false;
		}
		return true;
	}
	
	private void reset() {
		txtName.setText("");
		txtCooperateStartDate.setText("");
		txtCooperateEndDate.setText("");
		txtContactName1.setText("");
		txtContactPhone1.setText("");
		txtContactEmail1.setText("");
		txtContactName2.setText("");
		txtContactPhone2.setText("");
		txtContactEmail2.setText("");
		organizationComboViewer.setInput(internalOrganizationService.getAll());
		currentInternalOrganization = null;
	}
	
	private void fillOrganizationFields(InternalOrganization internalOrganization) {
		internalOrganization.setName(txtName.getText());
		try {
			internalOrganization.setCooperateStartDate(simpleDateFormat.parse(txtCooperateStartDate.getText()));
			if (StringUtils.isNotEmpty(txtCooperateEndDate.getText()))
				internalOrganization.setCooperateEndDate(simpleDateFormat.parse(txtCooperateEndDate.getText()));
			else
				internalOrganization.setCooperateEndDate(null);
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		internalOrganization.setContactName1(txtContactName1.getText());
		internalOrganization.setContactPhone1(txtContactPhone1.getText());
		internalOrganization.setContactEmail1(txtContactEmail1.getText());
		if (StringUtils.isNotEmpty(txtContactName2.getText())) {
			internalOrganization.setContactName2(txtContactName2.getText());
		} else {
			internalOrganization.setContactName2(null);
		}
		if (StringUtils.isNotEmpty(txtContactPhone2.getText())) {
			internalOrganization.setContactPhone2(txtContactPhone2.getText());
		} else {
			internalOrganization.setContactPhone2(null);
		}
		if (StringUtils.isNotEmpty(txtContactEmail2.getText())) {
			internalOrganization.setContactEmail2(txtContactEmail2.getText());
		} else {
			internalOrganization.setContactEmail2(null);
		}
	}
	
	private boolean checkInfo() {
		if(StringUtils.isEmpty(txtName.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入机构名称!");
			txtName.setFocus();
			return false;
		}
		if(StringUtils.isEmpty(txtCooperateStartDate.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入合作起始日期!");
			txtCooperateStartDate.setFocus();
			return false;
		}
		if(StringUtils.isEmpty(txtContactName1.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入联系人1姓名!");
			txtContactName1.setFocus();
			return false;
		}
		if(StringUtils.isEmpty(txtContactPhone1.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入联系人1电话!");
			txtContactPhone1.setFocus();
			return false;
		}
		if (StringUtils.isNotEmpty(txtContactEmail1.getText())
				&& !RegularUtils.emailCheck(txtContactEmail1.getText().trim())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "联系人1电邮输入不正确,请重新输入!");
			txtContactEmail1.setFocus();
			return false;
		}
		if (StringUtils.isNotEmpty(txtContactEmail2.getText())
				&& !RegularUtils.emailCheck(txtContactEmail2.getText().trim())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "联系人2电邮输入不正确,请重新输入!");
			txtContactEmail2.setFocus();
			return false;
		}
		return true;
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
